package cc.autoapi.pucong.liteflow.design.core.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
@AutoConfigureAfter({LiteFlowDesignConfiguration.class})
public class LiteFlowDesignWebMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private LiteFlowDesignConfiguration liteFlowDesignConfiguration;

    private final DesignCorsFilter designCorsFilter = new DesignCorsFilter();

    private boolean registerInterceptor = false;

    private boolean registerMapping = false;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        boolean enable = liteFlowDesignConfiguration.isEnable();
        if (enable) {
            String web = liteFlowDesignConfiguration.getWebPath();
            if (web != null && !registerMapping) {
                registerMapping = true;
                // 配置静态资源路径
                registry.addResourceHandler(web + "/**").addResourceLocations("classpath:/liteFlow-design-web/");
            }
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (!registerInterceptor) {
            registerInterceptor = true;
            AuthorizationInterceptor authorizationInterceptor = liteFlowDesignConfiguration.getAuthorizationInterceptor();
            registry.addInterceptor(new DesignWebRequestInterceptor(liteFlowDesignConfiguration.isSupportCrossDomain() ? designCorsFilter : null, authorizationInterceptor))
                    .addPathPatterns("/**");
        }
    }
}
